package com.interviewbackend.service.Impl;

import com.interviewbackend.client.QuestionGenerationClient;
import com.interviewbackend.entity.InterviewRecord;
import com.interviewbackend.entity.InterviewSession;
import com.interviewbackend.entity.SubQuestionFile;
import com.interviewbackend.mapper.InterviewRecordMapper;
import com.interviewbackend.mapper.InterviewSessionMapper;
import com.interviewbackend.mapper.SubQuestionFileMapper;
import com.interviewbackend.service.QuestionGenerationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class QuestionGenerationServiceImpl implements QuestionGenerationService {

    private final QuestionGenerationClient questionGenerationClient;
    private final InterviewSessionMapper interviewSessionMapper;
    private final InterviewRecordMapper interviewRecordMapper;
    private final SubQuestionFileMapper subQuestionFileMapper;

    @Autowired
    public QuestionGenerationServiceImpl(QuestionGenerationClient questionGenerationClient,
                                         InterviewSessionMapper interviewSessionMapper,
                                         InterviewRecordMapper interviewRecordMapper,
                                         SubQuestionFileMapper subQuestionFileMapper) {
        this.questionGenerationClient = questionGenerationClient;
        this.interviewSessionMapper = interviewSessionMapper;
        this.interviewRecordMapper = interviewRecordMapper;
        this.subQuestionFileMapper = subQuestionFileMapper;
    }

    @Override
    public String generateQuestion(Long interviewId, Integer roundIndex) {
        // Step 1: 获取面试会话信息（difficulty, style）
        InterviewSession interviewSession = interviewSessionMapper.selectById(interviewId);
        String difficulty = interviewSession.getDifficulty();
        String style = interviewSession.getStyle();

        // Step 2: 获取当前轮次已提过的问题
        List<InterviewRecord> interviewRecords = interviewRecordMapper.findByInterviewId(interviewId);
        List<String> questionHistory = interviewRecords.stream()
                .map(InterviewRecord::getQuestionText)
                .collect(Collectors.toList());

        // Step 3: 获取子题库的内容
        String subQuestionContent = "";
        SubQuestionFile subQuestionFile = subQuestionFileMapper.selectByInterviewId(interviewId);
        if (subQuestionFile != null) {
            subQuestionContent = new String(subQuestionFile.getContent(), StandardCharsets.UTF_8);
        }

        // Step 4: 使用 QuestionGenerationClient 生成新的面试问题
        return "questionGenerationClient.generateInterviewQuestion(difficulty, style, roundIndex, questionHistory, subQuestionContent)";
    }
}
